package com.liaoye.hellocustomview.util;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.util.Log;

public class BitmapUtil {

    public static Bitmap decodeBitmapFromResource(Resources resources, int resId, int reqWidth, int reqHeight) {

        final DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        reqWidth = (int) ((displayMetrics.scaledDensity * reqWidth) + 0.5f);
        reqHeight = (int) ((displayMetrics.scaledDensity * reqHeight) + 0.5f);

        Log.i("BitmapUtil", "decodeBitmapFromResource: reqWidth = " + reqWidth
                + " reqWidth =" + reqHeight);

        //获取图片的尺寸和类型
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, resId, options);

        //计算图片的压缩比例
        final int inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;

        //加载压缩后的图片进内存
        final Bitmap bitmap = BitmapFactory.decodeResource(resources, resId, options);

        Log.i("BitmapUtil", "decodeBitmapFromResource: width = " + bitmap.getWidth()
                + " height =" + bitmap.getHeight() + " byteCount = " + bitmap.getByteCount());

        return bitmap;
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;

        if (width > reqWidth || height > reqHeight) {
            final int halfWidth = width  / 2;
            final int halfHeight = height  / 2;

            while ((halfWidth / inSampleSize) >= reqWidth  && (halfHeight / inSampleSize) >= reqHeight) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }


}
